#include "websocketclient.h"

WebSocketClient::WebSocketClient(QObject *parent) : QObject(parent),m_pWebSocket(new QWebSocket(QString()))
{
    // 连接信号与槽
    connect(m_pWebSocket, &QWebSocket::connected, this, &WebSocketClient::onConnected);
    connect(m_pWebSocket, &QWebSocket::disconnected, this, &WebSocketClient::closed);

    connect(m_pWebSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived);
    connect(m_pWebSocket, &QWebSocket::binaryMessageReceived, this, &WebSocketClient::onBinaryMessageReceived);

    // 打开WebSocket连接
    m_pWebSocket->open(QUrl("ws://echo.websocket.org")); // 替换为你的WebSocket URL
}

void onConnected()
{
    qDebug() << "WebSocket connected.";
    // 发送文本消息
    m_pWebSocket->sendTextMessage(QStringLiteral("Hello WebSocket!"));
}

void closed()
{
    qDebug() << "WebSocket closed.";
}

void onTextMessageReceived(QString message)
{
    qDebug() << "Text Message received:" << message;
}

void onBinaryMessageReceived(QByteArray message)
{
    qDebug() << "Binary Message received:" << message.toHex();
}
